import json
from datetime import datetime

import mysql_util

"""云上农牧-添加权限"""


def find_org_id(orgCode):
    sql = "SELECT o1.CODE AS org_code, o1.id AS org_id, o1.flag, o1.business_id FROM pc_organization o1 WHERE 1 = 1 AND o1.CODE = '" + orgCode + "' and o1.level = '4'"
    rs = mysql_util.select_by_sql(sql)
    rs = json.loads(rs)
    # print(type(rs))
    if len(rs) > 0:
        info = rs[0]
        # print(info['farm_id'])
        return info['org_id']
    return None


def find_user_id(mobile: str) -> str:
    sql = "select id from pc_user where mobile = '" + mobile + "' and enabled = 1 limit 1"
    rs = mysql_util.select_by_sql(sql)
    rs = json.loads(rs)
    if len(rs) > 0:
        info = rs[0]
        # print(info['farm_id'])
        return info['id']
    return None


def insert_pc_user_organization(org_id, user_id):
    del_sql = "delete from pc_user_organization where organization_id = '{}' and \
            user_id = '{}'".format(org_id, user_id)
    insert_sql = "INSERT INTO pc_user_organization ( business_id,level,organization_id,user_id,create_user,create_time )\
    VALUES\
    (\
    '{}','{}','{}','{}','{}','{}'\
    )".format('10', '4', org_id, user_id, '6263', datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    # 删除
    mysql_util.execute(del_sql)
    # 新增
    mysql_util.execute(insert_sql)
    print('insert')


if __name__ == '__main__':
    org_code = '055322111'
    mobile = '18846439952'  # 刘长安
    # mobile = '17673606062' #卢云祥
    # mobile = '19811892125' #周津港
    # mobile = '13612168864' #弓彩文
    # mobile = '17600902615' #吴震
    # mobile = '15122696263'
    org_id = find_org_id(org_code)
    print('org_id=%s' % org_id)

    user_id = find_user_id(mobile)
    print('user_id=%s' % user_id)

    if org_id is None or user_id is None:
        print('绑定失败')
    else:
        insert_pc_user_organization(org_id, user_id)
        print('绑定成功!')
